package com.lyz.moil.server.service;

import com.lyz.moil.server.utils.OpenfireServerConfig;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 13-12-5
 * Time: 下午4:56
 * To change this template use File | Settings | File Templates.
 */

@Component
public class OpenfireServer {

    public static final Set<String> ONLINE_SET = new HashSet<String>();
    public static Connection connection;

    static {
        ConnectionConfiguration config = new ConnectionConfiguration(OpenfireServerConfig.OPEN_FIRE_HOST, OpenfireServerConfig.OPEN_FIRE_PORT);
        connection = new XMPPConnection(config);
    }


    public void reg(String userName, String password) throws XMPPException {
        if (!connection.isConnected()) connection.connect();
        AccountManager amgr = connection.getAccountManager();
        amgr.createAccount(userName, password);
        connection.disconnect();
    }

    public boolean checkUserIsExsit(String userName) throws XMPPException {
        if (!connection.isConnected()) connection.connect();
        AccountManager amgr = connection.getAccountManager();
        connection.disconnect();
        return false;
    }


    /**
     * 更改用户状态
     */
    public void setPresence(int code) {
        if (connection == null)
            return;
        Presence presence;
        switch (code) {
            case 0:
                presence = new Presence(Presence.Type.available);
                connection.sendPacket(presence);
//                Log.v("state", "设置在线");
                break;
            case 1:
                presence = new Presence(Presence.Type.available);
                presence.setMode(Presence.Mode.chat);
                connection.sendPacket(presence);
//                Log.v("state", "设置Q我吧");
                System.out.println(presence.toXML());
                break;
            case 2:
                presence = new Presence(Presence.Type.available);
                presence.setMode(Presence.Mode.dnd);
                connection.sendPacket(presence);
//                Log.v("state", "设置忙碌");
                System.out.println(presence.toXML());
                break;
            case 3:
                presence = new Presence(Presence.Type.available);
                presence.setMode(Presence.Mode.away);
                connection.sendPacket(presence);
//                Log.v("state", "设置离开");
                System.out.println(presence.toXML());
                break;
            case 4:
                Roster roster = connection.getRoster();
                Collection<RosterEntry> entries = roster.getEntries();
                for (RosterEntry entry : entries) {
                    presence = new Presence(Presence.Type.unavailable);
                    presence.setPacketID(Packet.ID_NOT_AVAILABLE);
                    presence.setFrom(connection.getUser());
                    presence.setTo(entry.getUser());
                    connection.sendPacket(presence);
                    System.out.println(presence.toXML());
                }
                // 向同一用户的其他客户端发送隐身状态
                presence = new Presence(Presence.Type.unavailable);
                presence.setPacketID(Packet.ID_NOT_AVAILABLE);
                presence.setFrom(connection.getUser());
                presence.setTo(StringUtils.parseBareAddress(connection.getUser()));
                connection.sendPacket(presence);
//                Log.v("state", "设置隐身");
                break;
            case 5:
                presence = new Presence(Presence.Type.unavailable);
                connection.sendPacket(presence);
//                Log.v("state", "设置离线");
                break;
            default:
                break;
        }
    }

    /**
     * 删除当前用户
     *
     * @param connection
     * @return
     */
    public boolean deleteAccount(XMPPConnection connection) {
        try {
            connection.getAccountManager().deleteAccount();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 修改密码
     *
     * @param connection
     * @return
     */
    public static boolean changePassword(XMPPConnection connection, String pwd) {
        try {
            connection.getAccountManager().changePassword(pwd);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 登录
     *
     * @param a 登录帐号
     * @param p 登录密码
     * @return
     */
    public boolean login(String a, String p) {
        try {
            if (connection == null)
                return false;
            /** 登录 */
            connection.login(a, p);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 连接服务器
     *
     * @return
     */
    public boolean conServer() {
        ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);
        /** 是否启用安全验证 */
        config.setSASLAuthenticationEnabled(false);
        /** 是否启用调试 */
        // config.setDebuggerEnabled(true);
        /** 创建connection链接 */
        try {
            connection = new XMPPConnection(config);
            /** 建立连接 */
            connection.connect();
            return true;
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 注册
     *
     * @param account  注册帐号
     * @param password 注册密码
     * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
     */
    public String regist(String account, String password) {
        if (connection == null)
            return "0";
        Registration reg = new Registration();
        reg.setType(IQ.Type.SET);
        //reg.setTo(ClientConServer.connection.getServiceName());
//        reg.setUsername(account);// 注意这里createAccount注册时，参数是username，不是jid，是“@”前面的部分。
//        reg.setPassword(password);
//        reg.addAttribute("android", "geolo_createUser_android");// 这边addAttribute不能为空，否则出错。所以做个标志是android手机创建的吧！！！！！
//        PacketFilter filter = new AndFilter(new PacketIDFilter(
//                reg.getPacketID()), new PacketTypeFilter(IQ.class));
//        PacketCollector collector = ClientConServer.connection
//                .createPacketCollector(filter);
        //ClientConServer.connection.sendPacket(reg);
//        IQ result = (IQ) collector.nextResult(SmackConfiguration
//                .getPacketReplyTimeout());
//        // Stop queuing results
//        collector.cancel();// 停止请求results（是否成功的结果）
//        if (result == null) {
//            Log.e("RegistActivity", "No response from server.");
//            return "0";
//        } else if (result.getType() == IQ.Type.RESULT) {
//            return "1";
//        } else { // if (result.getType() == IQ.Type.ERROR)
//            if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
//                Log.e("RegistActivity", "IQ.Type.ERROR: "
//                        + result.getError().toString());
//                return "2";
//            } else {
//                Log.e("RegistActivity", "IQ.Type.ERROR: "
//                        + result.getError().toString());
//                return "3";
//            }
//        }
        return "";
    }

}
